package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dto.input.BoreholeConditionInputDto;
import com.b511.swpu.cementbackend.service.PorePressureService;
import com.b511.swpu.cementbackend.entity.PorePressure;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.PorePressureRepository;
import com.b511.swpu.cementbackend.util.*;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.JoinType;
import java.util.Optional;

@Service
public class PorePressureServiceImpl implements PorePressureService {

    private final PorePressureRepository porePressureRepository;

    public PorePressureServiceImpl(PorePressureRepository porePressureRepository) {
        this.porePressureRepository = porePressureRepository;
    }

    @Override
    @Transactional
    public R updatePorePressure(Long id, PorePressure updatePorePressure) {
        Optional<PorePressure> optionalPorePressure = porePressureRepository.findById(id);
        if (!optionalPorePressure.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        PorePressure porePressure = optionalPorePressure.get();
        CopyUtil.copyProperties(updatePorePressure, porePressure);
        porePressureRepository.save(porePressure);
        return R.ok();
    }

    @Override
    public R getPorePressureByCondition(BoreholeConditionInputDto boreholeConditionInputDto, PageRequest pageRequest) {
        return R.ok().putData(porePressureRepository.findAll((Specification<PorePressure>) (root, cq, cb)
                -> Help.createPredicate(boreholeConditionInputDto, root.join("borehole", JoinType.LEFT), cb), pageRequest));
    }
}
